<template>
  <div class="container">
    <div class="questionsNew">
      <!-- 架子 -->
      <el-card>
        <!-- 标题 -->
        <p class="title">{{title}}</p>
        <!-- 表单 -->
        <el-form
          :model="addForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
          style="margin-left: 20px"
        >
          <!-- 学科(完成) -->
          <el-form-item label="学科" prop="subjectID">
            <el-select
              v-model="addForm.subjectID"
              placeholder="请选择"
              style="width: 400px"
              @change="handleChangeSubject"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in subjectNameList"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录（完成） -->
          <el-form-item label="目录" prop="catalogID">
            <el-select
              v-model="addForm.catalogID"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in catalogList"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业（完成） -->
          <el-form-item label="企业" prop="enterpriseID">
            <el-select
              v-model="addForm.enterpriseID"
              placeholder="请选择活动区域"
              style="width: 400px"
            >
              <el-option
                :label="item.company"
                :value="item.id"
                v-for="item in companyList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市" prop="province">
            <el-select
              v-model="addForm.province"
              placeholder="请选择"
              style="width: 196px; margin-right: 8px"
              @change="changeProvince"
            >
              <el-option
                v-for="item in provincesList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>

            <el-select
              v-model="addForm.city"
              placeholder="请选择"
              style="width: 196px"
            >
              <el-option
                v-for="item in citysList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向" prop="direction">
            <el-select
              v-model="addForm.direction"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in directionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型" prop="questionType">
            <el-radio-group v-model="addForm.questionType" @change="changeQuestionType">
              <el-radio :label="item.value" v-for="item in questionType" :key="item.value">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="addForm.difficulty">
              <el-radio :label="item.value" v-for="item in difficulty" :key="item.value">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干" prop="question">
            <!-- <div>富文本编辑器</div> -->
            <quillEditor v-model="addForm.question" v-focus></quillEditor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项" prop="options" v-if="addForm.questionType !== 3">

            <!-- 选项重构 -->
            <div class="option_item" v-for="item in addForm.options" :key="item.code">
              <!-- 单选 -->
              <el-radio :label="true"  v-model="item.isRight" v-if="addForm.questionType === 1" @change='changeRadioSelect(item.code)'>{{item.code}}</el-radio>
              <!-- 复选 -->
              <el-checkbox v-model="item.isRight" v-else :label="item.code" style="margin-right:30px;"></el-checkbox>
              <el-input style="width: 240px" v-model="item.title"></el-input>
              <!-- 图片上传组件 -->
              <ImageUpload class="avatar-uploader" v-model="item.img"></ImageUpload>
            </div>

            <el-button type="danger" :disabled="addForm.questionType !== 2" @click="addSelect">+增加选项与答案</el-button>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频" prop="videoURL">
            <el-input v-model="addForm.videoURL" style="width: 400px"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析" prop="answer">
            <!-- <div>富文本编辑器</div> -->
            <quillEditor v-model="addForm.answer"></quillEditor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注" prop="remarks">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="addForm.remarks"
              style="width: 400px"
            >
            </el-input>
          </el-form-item>
          <!-- 试题标签（完成） -->
          <el-form-item label="试题标签" prop="tags">
            <el-select
              v-model="tagsArray"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
              style="width: 400px"
              @change="changeTags"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 确认提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit" v-if="!this.addForm.id">确认提交</el-button>
            <el-button type="success" @click="onSubmit" v-else>确认修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import quillEditor from '../../module-hmmm/components/quill-editor.vue'
// 接口相关文件
import { simple } from '@/api/hmmm/subjects'
import { list } from '@/api/hmmm/companys'
import { add, detail, update } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
// 因为重名了需要改一个名字
import { simple as simple1 } from '@/api/hmmm/directorys'
import { simple as simpleTags } from '@/api/hmmm/tags'
// 图片上传组件
import ImageUpload from '../../module-hmmm/components/ImageUpload.vue'
export default {
  name: 'questionsNew',
  data () {
    return {
      // 表单绑定数据
      addForm: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: 1,
        // 难度
        difficulty: 1,
        // 题干
        question: '',
        // 选项
        options: [{
          // 代码
          code: 'A:',
          // 标题
          title: '',
          // 图片URL
          img: '',
          // 是否正确答案
          isRight: false
        }, {
          // 代码
          code: 'B:',
          // 标题
          title: '',
          // 图片URL
          img: '',
          // 是否正确答案
          isRight: false
        }, {
          // 代码
          code: 'C:',
          // 标题
          title: '',
          // 图片URL
          img: '',
          // 是否正确答案
          isRight: false
        }, {
          // 代码
          code: 'D:',
          // 标题
          title: '',
          // 图片URL
          img: '',
          // 是否正确答案
          isRight: false
        }],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: ''
      },
      // 城市选择列表
      cities: [],
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: ['blur', 'change'] }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: ['blur', 'change'] }
        ],
        questionType: [
          { required: true, message: '请输入题干', trigger: ['blur', 'change'] }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: ['blur', 'change'] }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: ['blur', 'change'] }
        ]
      },
      // 学科列表
      subjectNameList: [],
      // 企业列表
      companyList: [],
      // 城市列表
      provinces,
      provincesList: [],
      // 城市下的地区
      // citys,
      citysList: [],
      // 方向
      direction,
      directionList: [],
      // 目录列表
      catalogList: [],
      // 标签
      tagsList: [],
      // 题型
      questionType,
      // 难度
      difficulty,
      // 上传图片显示列表
      fileList: [],
      // 标签列表
      tagsArray: [],
      // 标题数据
      title: '试题录入',
      // 增加选项
      index: 4,
      // 拿到图片回显地址
      pic: ''
      // 回显假Id
      // id: this.$route.qurey.id || ''
    }
  },
  components: {
    quillEditor,
    ImageUpload
  },
  computed: {
    queryId () {
      const id = this.$route.query.id || ''
      return id
    }
  },
  directives: {
    focus: {
    // 指令的定义
      inserted: function (el) {
        el.focus()
      }
    }
  },
  created () {
    // 获取学科列表
    this.getsubjectNameList()
    // 获取企业列表
    this.getcompanyList()
    // console.log('省份', this.provinces)
    // 获取城市列表
    this.getprovincesList()
    // 获取方向列表数据
    this.getdirectionList()
    // 模拟数据回显(测试用)
    if (this.queryId) {
      this.getaddFormData()
    }
  },
  methods: {
    // 获取学科列表渲染下拉框
    async getsubjectNameList () {
      const { data: res } = await simple()
      // console.log('学科列表', res)
      this.subjectNameList = res
    },
    // 获取企业列表下拉框数据
    async getcompanyList () {
      const { data: res } = await list({ pagesize: 10000 })
      // console.log('企业列表', res)
      this.companyList = res.items
    },
    // 整合下拉列表数组转下拉列表需要的数据形式[{}]
    handleOpationsData (val) {
      const arr = []
      const result = val.map((item, index) => {
        arr.push({})
        arr[index].value = item
        arr[index].label = item
        return arr
      })[0]
      return result
    },
    // 整合城市列表数据渲染
    getprovincesList () {
      const result = this.provinces()
      // console.log('啥', result)
      this.provincesList = this.handleOpationsData(result)
    },
    // 整合城市下地区
    changeProvince () {
      // console.log('城市', this.addForm.province)
      const result = citys(this.addForm.province)
      this.citysList = this.handleOpationsData(result)
      // console.log('地区', this.citysList)
    },
    // 整合方向列表渲染
    getdirectionList () {
      this.directionList = this.handleOpationsData(direction)
    },
    // 切换学科 选择目录
    async handleChangeSubject () {
      // console.log('学科', this.addForm.subjectID)
      const { data: res } = await simple1({
        subjectID: this.addForm.subjectID
      })
      // console.log('目录', res)
      this.catalogList = res
      const { data: res1 } = await simpleTags({
        subjectID: this.addForm.subjectID
      })
      // console.log('标签', res1)
      this.tagsList = res1
    },

    // 处理tags标签
    changeTags () {
      this.addForm.tags = this.tagsArray.join('')
    },
    // 表单提交
    onSubmit () {
      // 预校验
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.addForm.id) {
            console.log('修改')
            this.title = '试题修改'
            // 校验通过 发送修改请求
            await update({
              ...this.addForm,
              questionType: `${this.addForm.questionType}`,
              difficulty: `${this.addForm.difficulty}`
            })
          } else {
            // 添加
            this.title = '试题录入'
            // 校验成功 发送请求
            const { data: res } = await add({
              ...this.addForm,
              questionType: `${this.addForm.questionType}`,
              difficulty: `${this.addForm.difficulty}`
            })
            console.log('添加成功否', res)
          }
        } else {
          console.log('error submit!!')
          return false
        }
        // 成功之后跳转基础题库列表
        this.$router.push('/questions/list')
        // 重置表单
        this.$refs.ruleForm.resetFields()
      })
    },
    // 多选增加选项
    addSelect () {
      // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

      const alphabet = Array.from(new Array(26), (ele, index) => {
        return String.fromCharCode(65 + index)
      })
      this.addForm.options.push({
        // 代码
        code: `${alphabet[this.index]}:`,
        // 标题
        title: '',
        // 图片URL
        img: '',
        // 是否正确答案
        isRight: false
      })
      this.index++
    },
    // 获取表单内容并回显
    async getaddFormData () {
      const { data: res } = await detail({ id: this.queryId })
      console.log('回显数据', res)
      this.addForm = res
      // 处理题型，难度数据
      this.addForm.questionType = +res.questionType
      this.addForm.difficulty = +res.difficulty
      // 处理标签数据
      this.tagsArray.push(res.tags)
      // 处理选择框
      this.addForm.options.forEach(item => {
        item.isRight = !!item.isRight
      })
      // 处理图片
    },
    // 处理单选按钮选中情况
    changeRadioSelect (val) {
      console.log('1', val)
      this.addForm.options.forEach(item => {
        if (item.code === val) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
    },
    // 切换题型重置表单
    changeQuestionType () {
      // console.log(1)
      this.addForm.options = [{
        // 代码
        code: 'A:',
        // 标题
        title: '',
        // 图片URL
        img: '',
        // 是否正确答案
        isRight: false
      }, {
        // 代码
        code: 'B:',
        // 标题
        title: '',
        // 图片URL
        img: '',
        // 是否正确答案
        isRight: false
      }, {
        // 代码
        code: 'C:',
        // 标题
        title: '',
        // 图片URL
        img: '',
        // 是否正确答案
        isRight: false
      }, {
        // 代码
        code: 'D:',
        // 标题
        title: '',
        // 图片URL
        img: '',
        // 是否正确答案
        isRight: false
      }]
    }
  }
}
</script>

<style scoped lang='less'>
.title {
  padding: 0px 20px 18px;
  border-bottom: 1px solid #ebeef5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.questionsNew {
  margin: 20px;
}
.select {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
/deep/ .el-upload--picture-card {
  width: 100px;
  height: 60px;
  position: relative;
  margin-left: 8px;
}
.option_item{
  padding-bottom: 20px;
}
.avatar-uploader{
    display: inline-block;
    vertical-align: middle;
    line-height: 1;
}
/deep/ .questionsNew .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 100px;
    height: 60px;
    line-height: 60px;
    margin-left: 6px;
}
.questionsNew .avatar-uploader i {
    position: absolute;
    right: 0;
    top: 0;
    -webkit-transform: translate(50%,-50%);
    transform: translate(50%,-50%);
    background: #fff;
    font-size: 18px;
    color: #999;
}
</style>
